import type { User } from "@/types/User";
import { defineStore } from "pinia";
import type { Status } from "@/types/Status";
import type { XtxResponse } from "@/types/Response";
import { AxiosError } from "axios";

type States = {
  // 用户信息
  profile: {
    // 记录用户信息
    result: Partial<User>;
    // 记录登录请求的请求状态
    status: Status;
    // 记录登录失败的错误信息
    error: string;
  };
};

type Getters = {};
type Actions = {
  // 用于实现登录的方法(账号登录、手机号登录)
  login(callback: () => Promise<XtxResponse<User>>): Promise<void>;
};

export const useUserStore = defineStore<"user", States, Getters, Actions>(
  "user",
  {
    state: () => ({
      profile: {
        result: {},
        status: "idle",
        error: "",
      },
    }),
    actions: {
      // 登录方法
      async login(callback) {
        // 更新请求状态
        this.profile.status = "loading";
        // 重置错误信息
        this.profile.error = "";
        // 捕获错误
        try {
          // 发送登录请求
          const response = await callback();
          // 保存登录之后用户信息
          this.profile.result = response.result;
          // 更新请求状态
          this.profile.status = "success";
        } catch (error) {
          // 更新请求状态
          this.profile.status = "error";
          // 记录错误信息
          if (error instanceof AxiosError) {
            this.profile.error = error.response?.data.message;
          } else if (error instanceof Error) {
            this.profile.error = error.message;
          }
        }
      },
    },
    persist: true,
  }
);
